import os
import shutil
import pandas as pd
import numpy as np
import time


q_id = 5
# markingver = 1
rootsubdir = 'submission_versions'
shutil.copy('final.csv', 'final.bak.csv')
score = pd.read_csv('final.csv')


allmks = []
alltimes = []
nosub = []

try:
    for idx in range(score.shape[0]):
        ver = int(score.iloc[idx]['Version'])
        # and int(score.iloc[idx]['Version']) == markingver:
        if np.isnan(score.iloc[idx]['Q5']) and score.iloc[idx]['Attendance'] == 'yes':
            sid = int(score.iloc[idx]['ID'])
            # open file
            subdir = os.path.join(rootsubdir, f"v{ver}")
            subs = os.listdir(subdir)
            files = list(filter(lambda x: x[:30] == f"CSCI3100 Final Exam_{sid}"
                                and x[-4:] in [".pdf", ".doc", ".zip", ".rar", "docx"]
                                and "receipt" not in x.lower()
                                and "vg" not in x.lower()
                                and "veriguide" not in x.lower(), subs))
            print(
                f"Marking {sid} ({idx+1}/{score.shape[0]} {100*(idx+1)/score.shape[0]:.2f}%)")
            print(f"Version: {ver}")

            if len(files) == 0:
                nosub.append(sid)
                print(f"No files {sid}")
                print(f"submissions:")
                print(
                    list(filter(lambda x: x[:30] == f"CSCI3100 Final Exam_{sid}", subs)))
                print()
                continue

            startT = time.time()
            for fid in files:
                print(f"File type: {fid[-4:]}")
                os.startfile(os.path.join(subdir, fid))

            mark = int(input(f"mark for Q{q_id}? "))
            score.iloc[idx, 3] = mark

            allmks.append(mark)

            elapsT = time.time() - startT
            print(f"Elapsed time: {elapsT:.2f} seconds\n\n")
            alltimes.append(elapsT)

            score.to_csv("final.csv", index=False)
except KeyboardInterrupt:
    try:
        score.to_csv("final.csv", index=False)
    except PermissionError:
        score.to_csv("final-error.csv", index=False)
except Exception as e:
    print("Error", e)
    score.to_csv("final-error.csv", index=False)

if len(allmks) > 0:
    print("\n")
    print("===========================")
    print(f"Count: {len(allmks)}")
    print(f"Mean: {np.mean(allmks):.2f}")
    print(f"Avg time: {np.mean(alltimes):.2f}")
    print("===========================")
